﻿using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mini.Model;

namespace Mini.Common
{
    public class FileHepler
    {
        public static async Task WriteStringToFile(string url, string htmlString)
        {
            using (var outfile = new StreamWriter(url, true, Encoding.UTF8))
            {
                await outfile.WriteAsync(htmlString);
            }
        }
        public static async Task UpdateStringToFile(string url, string htmlString)
        {
             await Task.Run(() => File.WriteAllText(url, htmlString));
        }
        public static async Task<string> ReadTextAsync(string filePath)
        {
            using (var sourceStream = new FileStream(filePath,
                FileMode.Open, FileAccess.Read, FileShare.Read,
                bufferSize: 4096, useAsync: true))
            {
                var sb = new StringBuilder();

                var buffer = new byte[0x1000];
                int numRead;
                while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                {
                    string text = Encoding.UTF8.GetString(buffer, 0, numRead);
                    sb.Append(text);
                }

                return sb.ToString();
            }
        }

        public static string GetFileNameFromUrl(string url, bool client = false)
        {
            var splitChar = !client ? '/' : '\\';
            return url.Split(splitChar)[url.Split(splitChar).Length - 1].ToString(CultureInfo.InvariantCulture);
        }

        public static IList<string> GetAllFileFromFolder(string folderUrl, string fileType = "")
        {
            var filesInDirectory = Directory.GetFiles(folderUrl);
            return string.IsNullOrWhiteSpace(fileType) ? filesInDirectory.ToList() : filesInDirectory.Where(extension => Path.GetExtension(extension) == fileType).ToList();
        }

        public static string IsFileExitsAndRename(string folderLink, string fileName)
        {
            var indexFolderInLink = fileName.IndexOf(folderLink, System.StringComparison.Ordinal); 

            if(indexFolderInLink == -1)
               fileName = Path.Combine(folderLink, fileName);

            var fileInfor = new FileInfo(fileName);

            if (!fileInfor.Exists) return fileName;
            var filePaths = Directory.GetFiles(folderLink);
            var countFile = filePaths.Count(c => Path.GetFileName(c) == fileName);
            var indexPoint = fileName.IndexOf(".", System.StringComparison.Ordinal);
            return fileName.Insert(indexPoint - 1, (countFile + 1).ToString(CultureInfo.InvariantCulture));
        }

        public static bool IsFolderExits(string folderLink)
        {
            return Directory.Exists(folderLink);
        }

        public static bool IsFont(string fileName)
        {
            return fileName.IndexOf(".eot", System.StringComparison.Ordinal) != -1 || fileName.IndexOf(".woff", System.StringComparison.Ordinal) != -1 || fileName.IndexOf(".ttf", System.StringComparison.Ordinal) != -1 || fileName.IndexOf(".svg", System.StringComparison.Ordinal) != -1;
        }

        public static async Task<PageModel> SavePage(string pageLink, string pageName, string saveTo)
        {
            var pageDirectory = DirectoryHelper.CreatePageDirectory(saveTo, pageName);
            var dataDownload = await DownloadHelper.DownloadString(pageLink);
            var fileName = string.Format("{0}.html", pageName);
            var fileDirectory = Path.Combine(pageDirectory, fileName);
            await WriteStringToFile(fileDirectory, dataDownload);
            await Task.Delay(500);
            return new PageModel
            {
                PageLink = pageLink,
                PageContent = dataDownload,
                PageDirectory = fileDirectory,
                PageName = pageName,
                PageStatus = PageStatus.Pending
            };
        }
    }
}
